import Taro from '@tarojs/taro'
import { View, Text, Form, CheckboxGroup, Checkbox, Radio, RadioGroup, Label, Button, PageContainer, Picker } from '@tarojs/components'
import { useEffect, useReducer, useRef, useState } from 'react'
import { AtButton, AtSearchBar, AtDrawer } from 'taro-ui'
import './index.scss'
import { hideLoading, reducer, showLoading, showModal } from '../../../utils'
import XCheckbox from '../../../components/XCheckbox'
import XLoadMore from '../../../components/XLoadMore'
import EditPage from './edit'
import { strategyListApi } from '../../../services/ChargeStrategy'
import { devicePaginationApi, setDeviceStrategyApi } from '../../../services/Device'
import GlobalData from '../../../global'

interface DeviceRow extends Device {
    checked:boolean
}

export default () => {
    let [state, stateDispatch] = useReducer(reducer, {
        isOpenPageContainer : false,
        pageContainerType : '',
        openShowEdit : false,
        editIng : false,
        isShowFilterAside : false,

        currentIndex : -1
    })

    let loadMoreRef = useRef<any>(null)
    let [currentDevice, setcurrentDevice] = useState<any>(null)
    let [filterParams, filterParamsDispatch] = useState<any>({})
    let [strategyList, setstrategyList] = useState<Strategy[]>([])
    let [dataList, setdataList] = useState<DeviceRow[]>([])
    let [selecteddeviceIds, setselecteddeviceIds] = useState<(string|number)[]>([])
    let [isAllSelected, setisAllSelected] = useState(false)


    function search() { //搜索
        setdataList([])
        loadMoreRef.current.reLoad()
    }

    function filterFormSubmit(params:any) {
        filterParamsDispatch({...params})
        search()
        stateDispatch({isShowFilterAside : false})
    }

    function toggleOpenEidtPageContainer(index:number) { //打开保存策略的page-container
        Taro.setNavigationBarTitle({
            title : '编辑设备'
        })
        setcurrentDevice(dataList[index])
        stateDispatch({isOpenPageContainer : true, currentIndex : index, pageContainerType : 'edit'})
    }
    function closePageContainer() { //关闭保存策略page-container触发的
        Taro.setNavigationBarTitle({
            title : '设备列表'
        })
        stateDispatch({isOpenPageContainer : false, currentIndex : -1})
    }
    function finishEditSaveDevice(device:Device|null) { //完成保存设备
        dataList[state.currentIndex] = Object.assign(dataList[state.currentIndex], device)
        stateDispatch({isOpenPageContainer : false})
    }

    
    function toggleEdit() {
        if(state.editIng == true) {
            changeSelect([])
        }

        stateDispatch({editIng : !state.editIng})
    }

    function toggleAllSelect(count:number) {
        if(count == 0) { //取消全选
            changeSelect([])
        }else { //全选
            changeSelect(dataList.map(item => String(item.deviceId!)))
        }
        
    }

    function changeSelect(values:Array<number|string>) {
        setselecteddeviceIds(values)
        dataList.forEach(item => {
            item.checked = values.includes(String(item.deviceId))
        })
        setdataList([...dataList])
    }

    function loadFinish(rows:Device[]) {
        if(rows.length > 0) {
            let newDataList:DeviceRow[] = [...dataList]
            rows.forEach(row => {
                newDataList.push({checked : false, ...row})
            })

            setdataList(newDataList)
        }
    }

    async function setDeviceStrategy(deviceIds:(number|string)[], index:number) {
        const devIds:number[] = deviceIds.map(devId => Number(devId))
        const strategy = strategyList[index]
        showLoading()
        const res = await setDeviceStrategyApi(devIds, strategy.strategyId as number)
        hideLoading()
        if(res.success) {
            const strategyName = strategy.strategyName
            dataList.forEach(data => {
                if(devIds.includes(Number(data.deviceId))) {
                    data.strategyName = strategyName
                    data.strategyId = strategy.strategyId
                }
            })
            setdataList([...dataList])
        }else {
            showModal('设置失败')
        }
    }
    

    useEffect(() => {
        if(selecteddeviceIds.length > 0 && (selecteddeviceIds.length == dataList.length)) {
            setisAllSelected(true)
        }else {
            setisAllSelected(false)
        }
    }, [selecteddeviceIds])

    useEffect(() => {
        strategyListApi().then(rows => {
            if(rows) {
                setstrategyList(rows)
            }
        })
    },[])
    
    return <>
        <View className='header'>
            <View className='flex-align-items-center p-r bc-fff'>
                {state.editIng
                ? <>
                    <View className='edit-operate'>
                        <View style='display:inline-block'>
                            <Picker disabled={selecteddeviceIds.length == 0} mode='selector' rangeKey='strategyName' range={strategyList} onChange={(e) => setDeviceStrategy(selecteddeviceIds, e.detail.value) } className='item'>
                                <AtButton disabled={selecteddeviceIds.length == 0} size='small'>设置策略</AtButton>
                            </Picker>
                        </View>
                        {/* <View style='display:inline-block' className='m-l-20'>
                            <AtButton className='item' size='small' disabled={selecteddeviceIds.length == 0} type='primary'>分配</AtButton>
                        </View>
                        <View style='display:inline-block' className='m-l-20'>
                            <AtButton className='item' size='small' disabled={selecteddeviceIds.length == 0} type='primary'>禁用</AtButton>
                        </View> */}
                    </View>
                    <View onClick={toggleEdit}>完成</View>
                </>
                : <>
                    <View className='flex-1'>
                        <AtSearchBar disabled={state.editIng} placeholder='设备名或设备号' value={filterParams.name} onChange={keyword => {filterParamsDispatch({name : keyword}) }} onConfirm={search} onActionClick={search}></AtSearchBar>
                    </View>
                    <View className='filter-icon' onClick={() => stateDispatch({isShowFilterAside : true})}></View>
                    <View className='edit-icon m-l-20' onClick={toggleEdit}></View>
                </>
                }
            </View>
            {state.editIng &&
                <View className='m-t-30 p-l-r'>
                    <CheckboxGroup onChange={e => toggleAllSelect(e.detail.value.length)}>
                        <XCheckbox checked={isAllSelected} indeterminate={!isAllSelected && selecteddeviceIds.length > 0} value={'1'}>{isAllSelected ? '取消全选' : '全选'}</XCheckbox>
                    </CheckboxGroup>
                </View>
            }
        </View>
        <CheckboxGroup onChange={e => { changeSelect(e.detail.value)  }}>
            {
                dataList.map((item, index) => <View className='row-item'>
                    <View className='flex-1'>
                        <View className='p-l-r'>
                            <View className='f-32'>设备名：<Text user-select>{item.deviceName}</Text></View>
                            <View className='color-999 m-t-10'>
                                <View>{GlobalData.deviceType[item.cate_1].name}/{GlobalData.deviceType[item.cate_1].children[item.cate_2].name}</View>
                                <View>设备号：<Text user-select>{item.deviceId}</Text></View>
                                <View>端口数：{item.portCount}，策略：{item.strategyName}</View>
                                {/* <View>连接状态：<Text className='color-f56c6c'>掉线</Text>，心跳时间：<Text>2012-12-12 12:12:12</Text></View> */}
                            </View>
                        </View>
                        <View className='bottom-nav p-l-r'>
                            <Picker mode='selector' rangeKey='strategyName' range={strategyList} onClick={() => stateDispatch({currentIndex : index})} onCancel={() => stateDispatch({currentIndex : -1}) } onChange={(e) => setDeviceStrategy([dataList[state.currentIndex].deviceId as number], e.detail.value) } className='item'>
                                <AtButton disabled={state.editIng} size='small'>设置策略</AtButton>
                            </Picker>
                            
                            <AtButton disabled={state.editIng} className='item' size='small' onClick={() => toggleOpenEidtPageContainer(index)}>编 辑</AtButton>
                        </View>
                    </View>
                    {state.editIng &&
                        <View className='p-l-r'>
                            <Checkbox checked={item.checked} value={String(item.deviceId)}></Checkbox>
                        </View>
                    }
                </View>)
            }
            
        </CheckboxGroup>

        <View style={'display:' + (state.editIng ? 'none' : 'block')}>
            <XLoadMore ref={loadMoreRef} queryParams={filterParams} onClick={params => devicePaginationApi(params)} pageSize={15} onFinish={rows => loadFinish(rows)} keyName='deviceId'></XLoadMore>
        </View>

        <AtDrawer show={state.isShowFilterAside} onClose={() => stateDispatch({isShowFilterAside : false})} right>
            <Form onSubmit={e => filterFormSubmit(e.detail.value)}>
                <View className='p-box'>
                    <View className='f-32'>策略类型</View>
                    <RadioGroup  name='type' className='flex-align-items-center m-t-20'>
                        <Label>
                            <Radio value='' checked={filterParams.type == ''}></Radio>全部
                        </Label>
                        <Label className='m-l-30'>
                            <Radio value='1'></Radio>计时
                        </Label>
                        <Label className='m-l-30'>
                            <Radio value='2'></Radio>计量
                        </Label>
                    </RadioGroup>
                </View>
                <View className='flex-align-items-center m-t-20 p-l-r'>
                    {/* <Button className='flex-1 f-28' formType='reset'>重 置</Button> */}
                    <Button className='flex-1 f-28 primary' formType='submit'>确 定</Button>
                </View>
            </Form>
        </AtDrawer>

        <PageContainer custom-style='z-index:10' show={state.isOpenPageContainer} position='center' onBeforeLeave={closePageContainer}>
            <View className='edit-container'>
                {state.isOpenPageContainer &&
                    <>
                        {state.pageContainerType == 'edit' &&
                            <EditPage device={currentDevice} onFinish={finishEditSaveDevice}></EditPage>
                        }
                        
                    </>
                }
            </View>
        </PageContainer>
    </>
}